﻿// -----------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
// -----------------------------------------------------------------------
using System;
using System.Reflection;
using Microsoft.Internal;

namespace System.ComponentModel.Composition.ReflectionModel
{
    internal class ExportingMember
    {
        private readonly ExportDefinition _definition;
        private readonly ReflectionMember _member;

        public ExportingMember(ExportDefinition definition, ReflectionMember member)
        {
            Assumes.NotNull(definition, member);

            _definition = definition;
            _member = member;
        }

        public bool RequiresInstance
        {
            get { return _member.RequiresInstance; }
        }

        public ExportDefinition Definition
        {
            get { return _definition; }
        }

        public CompositionResult<object> GetExportedObject(object instance)
        {
            CompositionResult result = CompositionResult.SucceededResult;

            try
            {
                object exportedObject = _member.GetValue(instance);

                return result.ToResult<object>(exportedObject);
            }
            catch (TargetInvocationException ex)
            {
                return result.MergeIssue(CompositionIssue.CreateIssueAsError(
                    CompositionIssueId.ExceptionDuringGettingOfExport,
                    ex.InnerException,
                    Strings.ExceptionDuringGettingOfExport,
                    this._member.Name,
                    this._member.DeclaringType.Name)).ToResult<object>(null);
            }
        }
    }
}
